package com.bluesmart.mia;

import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.Header;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.util.Constant;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;

import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.widget.TextView;
import android.widget.Toast;

public class AddDeviceConnectActivity extends BaseActivity implements
		OnClickListener {
	private String miasn = "";
	WifiManager mainWifi;
	
	private Handler wifiHandler = new Handler();
	Runnable runWifi=new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
			Log.d("bluesmart", "runWifi");
			WifiInfo wifiInfo =mainWifi.getConnectionInfo();
			if(wifiInfo!=null&&!wifiInfo.getSSID().contains(miasn))
			{
				wifiHandler.removeCallbacks(runWifi);
				cloudPair();
				
			}else
			{
				wifiHandler.postDelayed(runWifi, 1000);
			}
			
		}
	};
		
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_device_connect);

		((TextView) findViewById(R.id.center))
				.setText(getString(R.string.wifi_title_3));

		Intent intent = getIntent();
		miasn = intent.getStringExtra("miasn");
		miasn=miasn.replace("\"", "");
		miasn=miasn.replace("\\", "");

		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.cover).setOnClickListener(this);

		WebView webview = (WebView) findViewById(R.id.gif);
		webview.setHorizontalScrollBarEnabled(false);// 水平不显示
		webview.setVerticalScrollBarEnabled(false); // 垂直不显示
		String data = "<HTML><IMG src=\"file:///android_asset/connect.gif\"width=300;height=300/>";
		webview.loadDataWithBaseURL("file:///android_asset/connect.gif", data,
				"text/html", "utf-8", null);
		webview.setBackgroundColor(0x00000000);

		checkSys();
		// final Handler handle = new Handler(){
		// public void handleMessage(Message msg)
		// {
		// startActivity(new
		// Intent(AddDeviceConnectActivity.this,AddDeviceConnectSucActivity.class));
		// finish();
		// }
		// };
		//
		// new Timer().schedule(new TimerTask(){
		// @Override
		// public void run() {
		// handle.sendEmptyMessage(0);
		// }
		// }, 5000);
	}

	@Override
	public void onClick(View arg0) {
		if (R.id.left == arg0.getId())
			finish();
		else if (R.id.btn == arg0.getId()) {
			startActivity(new Intent(this, AddDeviceBareActivity.class));
			finish();
		}
	}

	// 实时检查mia 使用帐号密码上网的状态
	public void checkSys() {
		try {

			Log.d("bluesmart", "checkSys");			
			MgqRestClient.get("http://192.168.10.1/sys/", null,
					new AsyncHttpResponseHandler() {

						@Override
						public void onSuccess(int statusCode, Header[] headers,
								byte[] responseBody) {
							// TODO Auto-generated method stub
							Log.d("bluesmart", "checkSysonSuccess");
							String reposeString;
							try {

								reposeString = new String(responseBody, "utf-8");
								JSONObject jsonObject = null;
								jsonObject = JSONObject
										.parseObject(reposeString);
								JSONObject routes_Array = jsonObject
										.getJSONObject("connection");
								JSONObject routes_Array1 = routes_Array
										.getJSONObject("station");
								int configured = Integer.parseInt(routes_Array1
										.getString("configured"));
								int status = Integer.parseInt(routes_Array1
										.getString("status"));
								if (configured == 1 && status == 2) {

									Toast.makeText(getApplicationContext(),
											"配对成功", Toast.LENGTH_SHORT).show();
									//cloudPair();
									wifiHandler.postDelayed(runWifi, 1000);
								} else {
									// Toast.makeText(getApplicationContext(),
									// configured+"|"+status,
									// Toast.LENGTH_SHORT).show();
									Thread.sleep(500);
									checkSys();
								}

							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

						@Override
						public void onFailure(int statusCode, Header[] headers,
								byte[] responseBody, Throwable error) {
							// TODO Auto-generated method stub
							String reposeString = "";
							try {

								if(responseBody != null) reposeString = new String(responseBody, "utf-8");
								wifiHandler.postDelayed(runWifi, 1000);
								//cloudPair();
								// Toast.makeText(getApplicationContext(),
								// reposeString, Toast.LENGTH_LONG).show();

							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					});

		} catch (Exception e) {
			// TODO: handle exception
			String emeString = e.getMessage();
			Toast.makeText(getApplicationContext(), emeString,
					Toast.LENGTH_LONG).show();
		}
	}

	private int num = 0;

	public void cloudPair() {
		Log.d("bluesmart", "cloudPair");
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);
				Log.d("bluesmart", "cloudPair:"+response);

				if (ruser.getString("resCode").equals("1000")) {
					if (ruser.getString("pair").equals(miasn)) {
						Intent intent = new Intent(AddDeviceConnectActivity.this,
								AddDeviceConnectSucActivity.class);
						intent.putExtra("deviceid", miasn);
						startActivity(intent);
						finish();
					} else {
						num = num + 1;
						if (num < 30) {
							try {
								Thread.sleep(2000);
								cloudPair();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						} else {
							Toast.makeText(getApplicationContext(), "连接mia失败",
									Toast.LENGTH_LONG).show();
							startActivity(new Intent(AddDeviceConnectActivity.this,
									AddDeviceConnectFailActivity.class));
							finish();
						}
					}
				} else {
					num = num + 1;
					if (num < 30) {
						try {
							Thread.sleep(2000);
							cloudPair();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					} else {
						Toast.makeText(getApplicationContext(), "连接mia失败",
								Toast.LENGTH_LONG).show();
						
						
						startActivity(new Intent(AddDeviceConnectActivity.this,
								AddDeviceConnectFailActivity.class));
						finish();
					}
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] responseBody, Throwable error) {
				// TODO Auto-generated method stub
				Log.d("bluesmart", "cloudPair-error");
				num = num + 1;
				if (num < 30) {
					try {
						Thread.sleep(2000);
						cloudPair();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				} else {
					Toast.makeText(getApplicationContext(), "连接mia失败",
							Toast.LENGTH_LONG).show();
					startActivity(new Intent(AddDeviceConnectActivity.this,
							AddDeviceConnectFailActivity.class));
					finish();
				}
			}
		};

		String username = PreferencesUtils.getString(this, "username");
		String password = PreferencesUtils.getString(this, "password");
		if (username == null || username.length() == 0) {
			username = PreferencesUtils.getString(this, "username_tmp");
			password = PreferencesUtils.getString(this, "password_tmp");
		}

		JSONObject params = new JSONObject();
		params.put("mia_un", username);
		params.put("pwd", password);
		params.put("timezone", "");
		params.put("miasn", miasn);
		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/AppDevicePair.ashx",
				JSON.toJSONString(params), loginHandler);
	}
}
